'use client';

import { useState, useEffect } from 'react';
import Sidebar from '@/components/Sidebar';

export default function Settings() {  const [darkMode, setDarkMode] = useState(false);  const [currentApiIndex, setCurrentApiIndex] = useState(0);  const [username, setUsername] = useState('用户');  const [editingUsername, setEditingUsername] = useState(false);  const [tempUsername, setTempUsername] = useState('');  const [sidebarOpen, setSidebarOpen] = useState(false);  const [playInNewTab, setPlayInNewTab] = useState(true); // 默认在新标签页打开视频

  // 初始化主题
  useEffect(() => {
    // 检查本地存储的主题设置
    const savedTheme = localStorage.getItem('theme');
    const prefersColorScheme = window.matchMedia('(prefers-color-scheme: dark)');
    const systemPrefersDark = prefersColorScheme.matches;

    // 根据保存的设置或系统偏好设置主题
    if (savedTheme === 'light') {
      // 用户明确设置为亮色
      setDarkMode(false);
      document.documentElement.classList.remove('dark');
    } else if (savedTheme === 'dark') {
      // 用户明确设置为暗色
      setDarkMode(true);
      document.documentElement.classList.add('dark');
    } else {
      // 没有保存过主题，根据系统偏好设置
      setDarkMode(systemPrefersDark);
      if (systemPrefersDark) {
        document.documentElement.classList.add('dark');
        localStorage.setItem('theme', 'dark');
      } else {
        document.documentElement.classList.remove('dark');
        localStorage.setItem('theme', 'light');
      }
    }

    // 加载当前接口索引
    const savedApiIndex = localStorage.getItem('currentApiIndex');
    if (savedApiIndex) {
      setCurrentApiIndex(parseInt(savedApiIndex, 10));
    }

    // 加载用户名
    const savedUsername = localStorage.getItem('username');
    if (savedUsername) {
      setUsername(savedUsername);
    }
    
    // 加载视频播放方式设置
    const savedPlayInNewTab = localStorage.getItem('playInNewTab');
    if (savedPlayInNewTab !== null) {
      setPlayInNewTab(savedPlayInNewTab === 'true');
    }
  }, []);

  // 切换主题
  const toggleTheme = () => {
    const newTheme = !darkMode ? 'dark' : 'light';
    setDarkMode(!darkMode);
    
    if (newTheme === 'dark') {
      document.documentElement.classList.add('dark');
      localStorage.setItem('theme', 'dark');
    } else {
      document.documentElement.classList.remove('dark');
      localStorage.setItem('theme', 'light');
    }
    
    // 发送自定义事件通知其他页面主题变化
    window.dispatchEvent(new CustomEvent('themeChange', {
      detail: { theme: newTheme }
    }));
  };

  // 保存接口设置
  const saveApiIndex = (index: number) => {
    setCurrentApiIndex(index);
    localStorage.setItem('currentApiIndex', index.toString());
  };

  // 清除所有数据
  const clearAllData = () => {
    if (confirm('确定要清除所有数据吗？这将删除您的历史记录和收藏。')) {
      localStorage.removeItem('videoHistory');
      alert('所有数据已清除！');
    }
  };
  
  // 切换视频播放方式
  const togglePlayMode = () => {
    const newValue = !playInNewTab;
    setPlayInNewTab(newValue);
    localStorage.setItem('playInNewTab', newValue.toString());
    
    // 发送自定义事件通知其他页面播放模式变化
    window.dispatchEvent(new CustomEvent('playModeChange', {
      detail: { playInNewTab: newValue }
    }));
  };

  // 开始编辑用户名
  const startEditUsername = () => {
    setTempUsername(username);
    setEditingUsername(true);
  };

  // 保存用户名
  const saveUsername = () => {
    if (tempUsername.trim()) {
      setUsername(tempUsername.trim());
      localStorage.setItem('username', tempUsername.trim());
    }
    setEditingUsername(false);
  };

  // 取消编辑用户名
  const cancelEditUsername = () => {
    setEditingUsername(false);
  };

  return (
    <div className="flex h-full">
      {/* 侧边栏 */}
      <Sidebar 
        darkMode={darkMode} 
        username={username} 
        isOpen={sidebarOpen} 
        onToggle={() => setSidebarOpen(!sidebarOpen)} 
      />
      
      {/* 主内容区 */}
      <div className={`flex-1 md:ml-64 bg-white dark:bg-black min-h-screen text-black dark:text-white transition-all duration-300 ${
        sidebarOpen ? 'md:translate-x-0' : 'translate-x-0'
      }`}>
        {/* 顶部导航 */}
        <nav className="border-b border-gray-100 dark:border-gray-800">
          <div className="max-w-5xl mx-auto px-4 py-4 flex items-center">
            {/* 移动端汉堡菜单按钮 */}
            <button
              className="md:hidden mr-4 text-gray-600 dark:text-gray-400"
              onClick={() => setSidebarOpen(!sidebarOpen)}
              aria-label="打开菜单"
            >
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6">
                <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
              </svg>
            </button>
            <h1 className="text-xl font-medium">设置</h1>
          </div>
        </nav>

        <main className="max-w-5xl mx-auto px-4 py-8">
          <div className="space-y-8">
            {/* 用户信息 */}
            <section>
              <h2 className="text-lg font-medium mb-4">个人信息</h2>
              <div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="font-medium">用户名</p>
                    <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                      修改您的显示名称
                    </p>
                  </div>
                  {editingUsername ? (
                    <div className="flex items-center gap-2">
                      <input
                        type="text"
                        value={tempUsername}
                        onChange={(e) => setTempUsername(e.target.value)}
                        className="px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-black dark:text-white"
                        maxLength={20}
                      />
                      <button
                        onClick={saveUsername}
                        className="p-1 text-green-600 dark:text-green-400"
                        title="保存"
                      >
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                          <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
                        </svg>
                      </button>
                      <button
                        onClick={cancelEditUsername}
                        className="p-1 text-red-600 dark:text-red-400"
                        title="取消"
                      >
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                          <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                      </button>
                    </div>
                  ) : (
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium">{username}</span>
                      <button
                        onClick={startEditUsername}
                        className="p-1 text-gray-600 dark:text-gray-400 hover:text-black dark:hover:text-white"
                        title="编辑"
                      >
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                          <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" />
                        </svg>
                      </button>
                    </div>
                  )}
                </div>
              </div>
            </section>

            {/* 主题设置 */}
            <section>
              <h2 className="text-lg font-medium mb-4">外观</h2>
              <div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="font-medium">暗色模式</p>
                    <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                      切换界面暗色/亮色模式
                    </p>
                  </div>
                  <button
                    onClick={toggleTheme}
                    className="relative inline-flex items-center h-6 rounded-full w-11 bg-gray-200 dark:bg-gray-700"
                  >
                    <span
                      className={`${
                        darkMode ? 'translate-x-6' : 'translate-x-1'
                      } inline-block w-4 h-4 transform bg-white dark:bg-gray-300 rounded-full transition-transform duration-200 ease-in-out`}
                    />
                  </button>
                </div>
              </div>
            </section>
            
            {/* 视频播放设置 */}
            <section>
              <h2 className="text-lg font-medium mb-4">视频播放设置</h2>
              <div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="font-medium">在新标签页打开视频</p>
                    <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                      {playInNewTab ? '视频将在新标签页中打开' : '视频将在当前页面内嵌播放'}
                    </p>
                  </div>
                  <button
                    onClick={togglePlayMode}
                    className="relative inline-flex items-center h-6 rounded-full w-11 bg-gray-200 dark:bg-gray-700"
                  >
                    <span
                      className={`${
                        playInNewTab ? 'translate-x-6' : 'translate-x-1'
                      } inline-block w-4 h-4 transform bg-white dark:bg-gray-300 rounded-full transition-transform duration-200 ease-in-out`}
                    />
                  </button>
                </div>
              </div>
            </section>

            {/* 默认接口设置 */}
            <section>
              <h2 className="text-lg font-medium mb-4">解析接口</h2>
              <div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-4">
                <p className="font-medium mb-3">默认解析接口</p>
                <div className="space-y-2">
                  {['接口1', '接口2', '接口3', '接口4', '接口5'].map((api, index) => (
                    <div key={index} className="flex items-center">
                      <input
                        type="radio"
                        id={`api-${index}`}
                        name="default-api"
                        checked={currentApiIndex === index}
                        onChange={() => saveApiIndex(index)}
                        className="mr-2 h-4 w-4 text-black dark:text-white focus:ring-0"
                      />
                      <label htmlFor={`api-${index}`} className="text-sm">
                        {api}
                      </label>
                    </div>
                  ))}
                </div>
              </div>
            </section>

            {/* 数据管理 */}
            <section>
              <h2 className="text-lg font-medium mb-4">数据管理</h2>
              <div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-4">
                <div className="mb-4">
                  <p className="font-medium">清除所有数据</p>
                  <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    删除所有历史记录和收藏。此操作不可撤销。
                  </p>
                </div>
                <button
                  onClick={clearAllData}
                  className="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600 transition-colors"
                >
                  清除数据
                </button>
              </div>
            </section>
          </div>
        </main>

        {/* 页脚 */}
        <footer className="border-t border-gray-100 dark:border-gray-800 py-6 mt-12">
          <div className="max-w-5xl mx-auto px-4 text-center text-sm text-gray-500 dark:text-gray-400">
            <p>本工具仅用于学习和研究，请勿用于非法用途</p>
          </div>
        </footer>
      </div>
    </div>
  );
} 